package com.xp.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xp.service.AuthService;
import com.xp.utils.JwtUtil;
import com.xp.utils.Result;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

/**
 * JWT认证过滤器
 * 
 * @author xp
 * @since 2024-01-01
 */
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    private final JwtUtil jwtUtil;
    private final AuthService authService;
    private final ObjectMapper objectMapper;

    /**
     * 执行过滤逻辑
     * 
     * @param request HTTP请求
     * @param response HTTP响应
     * @param filterChain 过滤器链
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                  HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {
        
        try {
            // 获取请求路径
            String requestPath = request.getRequestURI();
            
            // 跳过不需要认证的路径
            if (shouldSkipAuthentication(requestPath)) {
                filterChain.doFilter(request, response);
                return;
            }

            // 从请求头中获取Token
            String token = extractTokenFromRequest(request);
            
            if (StringUtils.hasText(token)) {
                // 验证Token
                if (jwtUtil.validateToken(token)) {
                    // 检查Token是否在黑名单中
                    if (!authService.isTokenBlacklisted(token)) {
                        // 从Token中获取用户名
                        String username = jwtUtil.getUsernameFromToken(token);
                        
                        if (StringUtils.hasText(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                            // 创建认证对象
                            UsernamePasswordAuthenticationToken authentication = 
                                new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
                            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                            
                            // 设置到安全上下文
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                            
                            log.debug("用户 {} 认证成功", username);
                        }
                    } else {
                        log.warn("Token已被加入黑名单: {}", token);
                        handleAuthenticationError(response, "Token已失效");
                        return;
                    }
                } else {
                    log.warn("无效的Token: {}", token);
                    handleAuthenticationError(response, "Token无效或已过期");
                    return;
                }
            }
            
            filterChain.doFilter(request, response);
            
        } catch (Exception e) {
            log.error("JWT认证过程中发生错误", e);
            handleAuthenticationError(response, "认证失败");
        }
    }

    /**
     * 从请求中提取Token
     * 
     * @param request HTTP请求
     * @return Token字符串
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        // 从Authorization头中获取
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        
        // 从请求参数中获取
        String paramToken = request.getParameter("token");
        if (StringUtils.hasText(paramToken)) {
            return paramToken;
        }
        
        return null;
    }

    /**
     * 判断是否应该跳过认证
     * 
     * @param requestPath 请求路径
     * @return 是否跳过
     */
    private boolean shouldSkipAuthentication(String requestPath) {
        // 登录相关接口
        if (requestPath.startsWith("/auth/login") || 
            requestPath.startsWith("/auth/verify")) {
            return true;
        }
        
        // 健康检查接口
        if (requestPath.startsWith("/actuator/health")) {
            return true;
        }
        
        // Swagger文档接口
        if (requestPath.startsWith("/doc.html") || 
            requestPath.startsWith("/swagger-ui") || 
            requestPath.startsWith("/v3/api-docs") ||
            requestPath.startsWith("/swagger-resources") ||
            requestPath.startsWith("/webjars")) {
            return true;
        }
        
        // 静态资源
        if (requestPath.startsWith("/static/") || 
            requestPath.startsWith("/css/") || 
            requestPath.startsWith("/js/") || 
            requestPath.startsWith("/images/")) {
            return true;
        }
        
        return false;
    }

    /**
     * 处理认证错误
     * 
     * @param response HTTP响应
     * @param message 错误消息
     * @throws IOException IO异常
     */
    private void handleAuthenticationError(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        
        Result<Object> result = Result.error(401, message);
        String jsonResponse = objectMapper.writeValueAsString(result);
        
        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }
}